/*
 * Copyright 2011 J. Auer, J. Andert, F.-J. Jendrusch, U. Celebi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.fuberlin.replication.application.android.communication;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import de.fuberlin.replication.R;
import de.fuberlin.replication.application.android.RotatableAbstract;
import de.fuberlin.replication.communication.Communication;

/**
 * Android-specific communication manager.
 */
public class CommunicationManager extends RotatableAbstract implements CommunicationHelper {
	/** Communication type dialog id. */
	public static final int DIALOG_COMMUNICATION_TYPE = 1;

	/** Communication type dialog wait semaphore. */
	Semaphore wait;

	/** Communication type list. */
	List<CommunicationType> types = new ArrayList<CommunicationType>();

	/** Communication type-specific communication helper. */
	CommunicationHelper helper;

	@Override
	public synchronized void setActivity(Activity activity) {
		super.setActivity(activity);

		if (helper != null)
			helper.setActivity(activity);
	}

	/**
	 * Returns the communication type list.
	 * 
	 * @return the communication type list.
	 */
	public List<CommunicationType> getTypes() {
		return types;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (helper != null)
			helper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
			case DIALOG_COMMUNICATION_TYPE:
				String[] names = new String[types.size()];

				for (int i = 0; i < names.length; i++)
					names[i] = getActivity().getString(types.get(i).getNameId());

				AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
				builder.setTitle(R.string.dialog_communication_type_title);
				builder.setItems(names, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int item) {
						helper = types.get(item).getCommunicationHelper();
						helper.setActivity(getActivity());

						wait.release();
					}
				});
				builder.setCancelable(true);
				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						wait.release();
					}
				});

				return builder.create();
			default:
				if (helper != null)
					return helper.onCreateDialog(id, args);

				break;
		}

		return null;
	}

	@Override
	public void onPrepareDialog(int id, Dialog dialog, Bundle args) {
		if (helper != null)
			helper.onPrepareDialog(id, dialog, args);
	}

	@Override
	public Communication getCommunication() {
		if (helper == null)
			throw new IllegalStateException("Synchronization not yet started");

		return helper.getCommunication();
	}

	@Override
	public void onSynchronizationStart() {
		wait = new Semaphore(0);

		getUIHandler().obtainMessage(UICallback.MESSAGE_DIALOG_SHOW, DIALOG_COMMUNICATION_TYPE, 0).sendToTarget();

		wait.acquireUninterruptibly();
		wait = null;

		getUIHandler().obtainMessage(UICallback.MESSAGE_DIALOG_REMOVE, DIALOG_COMMUNICATION_TYPE, 0).sendToTarget();

		if (helper == null)
			throw new IllegalStateException();

		helper.onSynchronizationStart();
	}

	@Override
	public void onSynchronizationException(Exception e) {
		if (helper != null)
			helper.onSynchronizationException(e);
	}

	@Override
	public void onSynchronizationStop() {
		if (helper != null)
			try {
				helper.onSynchronizationStop();
			} finally {
				helper = null;
			}
	}
}